<template>
  <div>
    <table border="1">
      <tr>
        <td>序号</td>
        <td>商品名称</td>
        <td>商品价格</td>
        <td>购买数量</td>
        <td>操作</td>
      </tr>
      <tr v-for="(item, index) in glist">
        <th>{{ index+1 }}</th>
        <th>{{ item.name }}</th>
        <th>{{ item.price }}</th>
        <th>
          <button @click="reduce(index)">-</button>
          {{ item.count }}
          <button @click="add(index)">+</button>
        </th>
        <th>
          <button @click="deleted(index)">移除</button>
        </th>
      </tr>
    </table>
    总价：￥{{ total }}
  </div>
</template>

<script>
  export default {
    name: "job",
    // 数据容器
    data() {
      return {
        glist: [
          {'name': 'iphone 5s', 'price': 500, 'count': 0},
          {'name': 'iphone 6', 'price': 800, 'count': 0},
          {'name': 'iphone 6s', 'price': 1200, 'count': 0}
          ],
        total: 0,
      }
    },
    // 钩子方法
    mounted() {

    },
    // 自定义方法
    methods: {
      // 减少商品数量
      reduce: function (index) {
        if (this.glist[index].count <= 0){
          alert('不能再减了')
          return;
        }
        else{
          this.glist[index].count--;
        }
        this.addprice()
      },

      // 增加商品数量
      add: function (index) {
        this.glist[index].count++;
        this.addprice()
      },

      // 减少商品数量
      deleted: function (index) {
        let price = 0;
        for (let i = 0; i < this.glist.length; i++){
          if (this.glist[i] == this.glist[index])
          price = price + this.glist[i].price * this.glist[i].count
        }
        this.total = this.total - price
        this.glist.splice(index, 1);
      },

      // 总价
      addprice: function () {
        let price = 0;
        for (let i = 0; i < this.glist.length; i++) {
          if (this.glist[i].count !==0){
            price = price + this.glist[i].price * this.glist[i].count
          }
        }
        this.total = price
      }
    }
  }
</script>

<style scoped>

</style>
